// 新增活动弹窗组件
import React, { useEffect } from 'react'
import useKeepState from 'use-keep-state'
import {
  createActivities,
  updateActivities,
} from '../../../../request/activities'
import { Modal, Form, Input } from 'antd'

type Props = {
  visible: boolean
  rowData?: { [key: string]: any }
  onSuccess: (res?: any) => void
  onCancel: () => void
}
const { TextArea } = Input
const initialState = {
  confirmLoading: false,
  content: '',
}

const CreateActivity: React.FC<Props> = function ({
  visible,
  rowData,
  onSuccess,
  onCancel,
}: Props) {
  const [form] = Form.useForm()
  const [state, setState] = useKeepState(initialState)
  async function handleSubmitForm() {
    try {
      const values = await form.validateFields()
      const data = {
        content: values.content.trim(),
      }
      ;(rowData
        ? updateActivities(rowData.id, data)
        : createActivities(data)
      ).then(res => {
        if (res.data.success) {
          onSuccess()
        }
      })
    } catch {}
  }

  useEffect(() => {
    if (visible && rowData) {
      form.setFieldsValue({
        content: rowData.content,
      })
    }
  }, [visible, rowData])

  useEffect(() => {
    if (!visible) {
      form.resetFields()
    }
  }, [visible])

  return (
    <Modal
      title="新增"
      visible={visible}
      onOk={handleSubmitForm}
      onCancel={onCancel}
      confirmLoading={state.confirmLoading}
      forceRender
      maskClosable={false}
    >
      <Form form={form}>
        <Form.Item
          label="活动内容"
          name="content"
          rules={[{ required: true, message: '请输入内容', whitespace: true }]}
        >
          <TextArea
            rows={3}
            value={state.content}
            onChange={e => setState({ content: e.target.value })}
            maxLength={250}
            placeholder="请输入内容"
          ></TextArea>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default React.memo(CreateActivity)
